﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yunpian.Sdk;
using Yunpian.Sdk.Model;

namespace Developer.Service
{
    public class SMSService
    {

            /// <summary>
            /// 服务器HTTP地址
            /// </summary>
            private static string BASE_URI = "http://sms.yunpian.com";

            /// <summary>
            /// 服务版本号
            /// </summary>      
            private static string VERSION = "v2";

            /// <summary>
            /// 查账户信息的http地址 
            /// </summary>           
            private static string URI_GET_USER_INFO = BASE_URI + "/" + VERSION + "/user/get.json";

            /// <summary>
            /// 通用接口发短信的http地址 
            /// </summary>
            private static string URI_SEND_SMS = BASE_URI + "/" + VERSION + "/sms/single_send.json";

            /// <summary>
            /// 模板接口短信接口的http地址 
            /// </summary>
            private static string URI_TPL_SEND_SMS = BASE_URI + "/" + VERSION + "/sms/tpl_single_send.json";

            /// <summary>
            /// 通用接口查回复的短信的http地址 
            /// </summary>
            private static string URI_GET_REPLY = BASE_URI + "/" + VERSION + "/sms/get_reply.json";

            /// <summary>
            /// APIKEY
            /// </summary>
            private static string APIKEY = "012083ce0cf573aff8fa29b8dbc467ac";

            /// <summary>
            /// 获取用户信息
            /// </summary>
            /// <returns>Json格式</returns>
            public static string GetUserInfo()
            {
                System.Net.WebRequest req = System.Net.WebRequest.Create(URI_GET_USER_INFO + "?apikey=" + APIKEY);
                System.Net.WebResponse resp = req.GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                return sr.ReadToEnd().Trim();
            }

            /// <summary>
            ///  发短信通用接口
            /// </summary>
            /// <param name="text">短信内容</param>
            /// <param name="mobile">接收的手机号码,有多个手机号则用逗号分隔，一次最多100个手机号码</param>
            /// <returns>Json格式</returns> 
            public static SmsSingleSend SendSms(string text, string mobile)
            {
                var clnt = new YunpianClient(APIKEY).Init();
                //发送短信API
                var param = new Dictionary<string, string>
                {
                    [Const.Mobile] = mobile,
                    [Const.Text] = text
                };
                var r = clnt.Sms().SingleSend(param);
                //获取返回结果, 返回码:r.Code, 返回码描述:r.Msg, API结果:r.Data, 其他说明:r.Detail, 调用异常:r.E

                //账户:clnt.User().* 签名:clnt.Sign().* 模版:clnt.Tpl().* 短信:clnt.Sms().* 视频短信:clnt.VideoSms().* 语音:clnt.Voice().* 短链接:clnt.ShortUrl().*

                //释放clnt
                clnt.Dispose();
                return r.Data;


            }

            /// <summary>
            /// 模板接口发短信
            /// </summary>
            /// <param name="tpl_id">模板ID</param>
            /// <param name="mobile">接收的手机号码</param>
            /// <param name="tpl_value">模板变量值</param>
            /// <returns>Json格式</returns>
            public static string TplSendSms(long tpl_id, string mobile, string tpl_value)
            {
                string postDataStr = "apikey=" + APIKEY + "&mobile=" + mobile + "&tpl_id=" + tpl_id.ToString() + "&tpl_value=" + tpl_value;
                return HttpPost(URI_TPL_SEND_SMS, postDataStr);
            }

            /// <summary>
            /// 查回复的短信
            /// </summary>
            /// <param name="page_num">页码，从1开始</param>
            /// <param name="page_size">每页个数，最大100个</param>
            /// <param name="mobile">接收的手机号码</param>
            /// <returns>Json格式</returns>
            public static string GetReplySms(int page_num, int page_size, string mobile, string datastart, string dataend)
            {
                DateTime now = DateTime.Now;
                //string datastart = now.AddDays(-3).ToString("yyyy-MM-dd 00:00:00");
                //string datasend = now.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
                string postDataStr = "apikey=" + APIKEY + "&start_time=" + datastart + "&end_time=" + dataend
                    + "&page_num=" + page_num + "&page_size=" + page_size + "&mobile=" + mobile;

                return HttpPost(URI_GET_REPLY, postDataStr);
            }

            /// <summary>
            /// 通用接口请求
            /// </summary>
            /// <param name="Url"></param>
            /// <param name="postDataStr"></param>
            /// <returns></returns>
            public static string HttpPost(string Url, string postDataStr)
            {
                byte[] dataArray = Encoding.UTF8.GetBytes(postDataStr);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = dataArray.Length;
                //request.CookieContainer = cookie;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(dataArray, 0, dataArray.Length);
                dataStream.Close();
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    String res = reader.ReadToEnd();
                    reader.Close();
                    return res;
                }
                catch (Exception e)
                {
                    return e.Message + e.ToString();
                }
            }
            public static int GetValidCode(int minValue, int maxValue)
            {
                Random rand = new Random((int)DateTime.Now.Ticks);
                int item = minValue;
                for (int i = minValue; i <= maxValue; i++)
                {
                    item = rand.Next(minValue, maxValue + 1);
                }
                return item;
            }
        }

}
